package com.web.service.impl;

import com.business.dao.LoanMapper;
import com.business.domain.CarModelVo;
import com.business.domain.LoanPlan;
import com.business.domain.LoanScheme;
import com.business.domain.LoanVo;
import com.web.service.CarLoanPlanService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service("carLoanPlanService")
public class CarLoanPlanServiceImpl implements CarLoanPlanService {

    @Resource
    private LoanMapper loanMapper;

    @Override
    public List<LoanScheme> getAllLoanPlan(CarModelVo modelVo, LoanVo loanVo, Double chejia) {
        List<LoanScheme> list = new ArrayList<LoanScheme>();
        List<LoanScheme> loanPlan1 = this.getLoanPlan(modelVo, loanVo, "1", chejia);
        List<LoanScheme> loanPlan2 = this.getLoanPlan(modelVo, loanVo, "2", chejia);
        List<LoanScheme> loanPlan3 = this.getLoanPlan(modelVo, loanVo, "3", chejia);

        if (loanPlan1 != null && loanPlan1.size() > 0) {
            list.add(loanPlan1.get(0));
        }
        if (loanPlan2 != null && loanPlan2.size() > 0) {
            list.add(loanPlan2.get(0));
        }
        if (loanPlan3 != null && loanPlan3.size() > 0) {
            list.add(loanPlan3.get(0));
        }
        return list;
    }

    @Override
    public List<LoanScheme> getLoanPlan(CarModelVo modelVo, LoanVo loanVo, String type, Double chejia) {
        if (chejia == null || chejia == 0) {
            return null;
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("installment", loanVo.getInstallment().toString());
        map.put("payment", loanVo.getPayment().toString());

        BigDecimal guidePrice = modelVo.getGuidePrice() == null ? new BigDecimal(0) : modelVo.getGuidePrice();// 车价

        List<LoanVo> bankList = loanMapper.getBankList(map);
        List<LoanVo> p2pList = loanMapper.getP2PList(map);

        //存储每个贷款方案
        List<LoanScheme> itemList = new ArrayList<LoanScheme>();
        Collections.sort(p2pList, new Comparator<LoanVo>() {
            @Override
            public int compare(LoanVo o1, LoanVo o2) {
                if (!o1.getAmount().equals(o2.getAmount())) {
                    // 年龄相同则按姓名排序
                    return (int) (o2.getAmount() - o1.getAmount());
                } else if (o1.getRate() != o2.getAmount()) {
                    // 姓名也相同则按学号排序
                    return (int) (o1.getRate() - o2.getRate());
                } else {
                    return 0;
                }
            }
        });
        String name = modelVo.getBrandName();//品牌名
        for (LoanVo pro : bankList) {
            Double money = guidePrice.doubleValue();//贷款总额
            LoanScheme scheme = new LoanScheme();
            if (money <= 0) {
                break;
            }
            //把银行或者需要抵押的产品放进 无抵押的list 排序
            p2pList.add(pro);
            if ("1".equals(type)) {//利率最低
                Collections.sort(p2pList, new Comparator<LoanVo>() {
                    @Override
                    public int compare(LoanVo o1, LoanVo o2) {
                        if (o1.getRate() > o2.getRate()) {
                            return 1;
                        }
                        if (o1.getRate() < o2.getRate()) {
                            return -1;
                        }
                        return 0;
                    }
                });
            } else if ("2".equals(type)) {//周期最短
                Collections.sort(p2pList, new Comparator<LoanVo>() {
                    @Override
                    public int compare(LoanVo o1, LoanVo o2) {
                        // 先排年龄
                        if (!o1.getPeriod().equals(o2.getPeriod())) {
                            return o1.getPeriod() - o2.getPeriod();
                        }
                        return 0;

                    }
                });
            } else if ("3".equals(type)) {//线上 最快
                Collections.sort(p2pList, new Comparator<LoanVo>() {
                    @Override
                    public int compare(LoanVo o1, LoanVo o2) {
                        int o1p = Integer.parseInt(o1.getPlace()) == 0 ? 1 : Integer.parseInt(o1.getPlace());
                        int o2p = Integer.parseInt(o2.getPlace()) == 0 ? 1 : Integer.parseInt(o2.getPlace());
                        // 先排年龄
                        if (o1p != o2p) {
                            return o1p - o2p;
                        }
                        return 0;

                    }
                });
            }
            //循环p2pList  贷款
            //存储贷每个贷款产品的详情
            List<LoanPlan> loanPlanList = new ArrayList<LoanPlan>();
            Double totalMoney = (double) 0;//每个方案的总还款额
            Double totalAccrual = (double) 0;//每个方案的总还款额
            StringBuilder duplicate = new StringBuilder();
            for (LoanVo loanPlan : p2pList) {
                double rate = loanPlan.getRate();//利率
                // 判断是否限定品牌
                String brand = loanPlan.getLimitedBrands();
                if (StringUtils.isEmpty(brand) || (!StringUtils.isEmpty(brand) && brand.indexOf(name) > 0)) {
                    Double maxMoney = loanPlan.getAmount();// 最大总额
                    double rateMaxMoney = loanPlan.getAmountScale() / 100 * chejia;// 按比例最大总额
                    double productMaxMoney = maxMoney > rateMaxMoney ? rateMaxMoney : maxMoney;// 最终贷款额度
                    Double curProductDaiMoney;
                    LoanPlan item = new LoanPlan();
                    if (money <= productMaxMoney) {// 可以贷款到的金额
                        curProductDaiMoney = money;
                        item.setMoney(curProductDaiMoney);//贷款金额
                        //利息
                        Double lixi = curProductDaiMoney * rate * loanVo.getInstallment() / 100;
                        item.setAccrual(lixi);//利息 = 本金*利息*月数
                        item.setTotalMoney(lixi + curProductDaiMoney);//总还款额
                        totalMoney += lixi + curProductDaiMoney;
                        totalAccrual += lixi;
                        item.setLoanVo(loanPlan);
                        duplicate.append(loanPlan.getId()).append(",");
                        loanPlanList.add(item);
                        break;
                    } else {
                        curProductDaiMoney = productMaxMoney;
                        money = money - curProductDaiMoney;
                        item.setMoney(curProductDaiMoney);
                        //利息
                        Double lixi = curProductDaiMoney * rate * loanVo.getInstallment() / 100;
                        item.setAccrual(lixi);//利息 = 本金*利息*月数
                        item.setTotalMoney(lixi + curProductDaiMoney);//总还款额
                        totalMoney += lixi + curProductDaiMoney;
                        totalAccrual += lixi;
                        duplicate.append(loanPlan.getId()).append(",");
                        item.setLoanVo(loanPlan);
                        loanPlanList.add(item);
                    }
                }
            }
            scheme.setPlanList(loanPlanList);
            scheme.setTotalMoney(totalMoney);
            scheme.setTotalAccrual(totalAccrual);
            scheme.setDuplicate(duplicate.toString());
            itemList.add(scheme);
            p2pList.remove(pro);
        }
        Collections.sort(itemList, new Comparator<LoanScheme>() {
            @Override
            public int compare(LoanScheme o1, LoanScheme o2) {
                if (o1.getTotalMoney() > o2.getTotalMoney()) {
                    return 1;
                }
                if (o1.getTotalMoney() < o2.getTotalMoney()) {
                    return -1;
                }
                return 0;
            }
        });
        for (int i = 0; i < itemList.size(); i++) {
            if (guidePrice.doubleValue() >= itemList.get(i).getTotalMoney()) {
                itemList.remove(i);
                i--;
            }
        }
        return quChong(itemList);
    }

    /**
     * 最后方案去重复 并返回三个方案
     */
    private List<LoanScheme> quChong(List<LoanScheme> itemList) {
        for (int i = 0; i < itemList.size(); i++) { // 外循环是循环的次数
            for (int j = itemList.size() - 1; j > i; j--) { // 内循环是 外循环一次比较的次数
                if (itemList.get(i).getDuplicate().equals(itemList.get(j).getDuplicate())) {
                    itemList.remove(j);
                }
            }
        }
        return itemList;
    }

}
